﻿using AnesSystem.Controls;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AnesSystem.Models;
using System.Windows;
using AnesSystem.Util;

using Common;
using AnesSystem.Services;

namespace AnesSystem.ViewModels.Operation.CQ.CQTL
{
    public class MedicineConfigCtrlViewModel : BaseViewModel<MedicineConfigCtrlViewModel>
    {
        #region Variables
        private ObservableCollection<AnesSystem.Controls.Operation.CQ.CQTL.MedicineElementCtrl> _listCtrl;
        private List<ConfigDrugMethodsModel> _configDrugMethodsModelList;
        private List<ConfigChannelsModel> _configChannelsModelList;
        private ConfigDrugsModel _selectedDrug;

        private ConfigDrugMethodsModel _selectedDrugMethod;
        private FrameworkElement _drugMethodCtrl;
        private Dictionary<string, FrameworkElement> _drugMethodCtrlList;
        private PatientDrugsModel _patientDrugsModelCopy;
        private PatientDrugsModel _patientDrugsModel;
        private Visibility _leftPanlVisibly;
        private ObservableCollection<LeftDrugModel> _listLeftDrug;
        private LeftDrugModel _selectedLeftDrug;
        private BaseDrugMethodCtrl ctrl = new BaseDrugMethodCtrl();
        private DateTime _pauseTime = DateTime.Now;
        private DateTime _recoverTime = DateTime.Now;

        private bool _finishCheckBox;
        private bool _takeCheckBox;
        bool _maZuiIsCheck;
        bool _shuYeIsCheck;

        private Visibility _finishTimeVisibility;
        private Visibility _takeCheckBoxVisibility;
        private Visibility _takeTextBlockVisibility;
        private Visibility _takeAmountVisibility;
        private Visibility _totalAmountUnitVisibility;

        private Visibility _pauseButtonVisibility;
        private Visibility _recoverButtonVisibility;
        private Visibility _deleteButtonVisibility;
        private Visibility _saveAndContinueButtonVisibility;


        private List<CustomEDBtnCtrl> _displayDrugCtrlList;
        private Dictionary<string, List<ConfigDrugsModel>> _drugList;
        private ObservableCollection<ConfigDrugGroupTypesModel> _drugTypeGroupList;
        private Dictionary<string, List<CustomEDBtnCtrl>> _drugCtrlList;
        private ObservableCollection<CommonTypeCellCtrl> _drugTypeCtrlList;
        private CommonTypeCellCtrl _currentSelType;

        #endregion

        #region 构造函数

        public MedicineConfigCtrlViewModel()
        {
            DisplayDrugCtrlList = new List<CustomEDBtnCtrl>();
            DrugList = new Dictionary<string, List<ConfigDrugsModel>>();
            DrugTypeGroupList = new ObservableCollection<ConfigDrugGroupTypesModel>();
            DrugCtrlList = new Dictionary<string, List<CustomEDBtnCtrl>>();
            DrugTypeCtrlList = new ObservableCollection<CommonTypeCellCtrl>();
            CurrentSelType = new CommonTypeCellCtrl();

            _configChannelsModelList = DataManager.Instance.ConfigChannelsModelList.ToList();
            _configDrugMethodsModelList = DataManager.Instance.ConfigDrugMethodsModelList.ToList().Where(O => O.Single == false).ToList();

            _pauseButtonVisibility = Visibility.Hidden;
            _recoverButtonVisibility = Visibility.Hidden;
            _deleteButtonVisibility = Visibility.Hidden;
            _saveAndContinueButtonVisibility = Visibility.Hidden;
            _leftPanlVisibly = Visibility.Collapsed;
            _listCtrl = new ObservableCollection<AnesSystem.Controls.Operation.CQ.CQTL.MedicineElementCtrl>();
            _listLeftDrug = new ObservableCollection<LeftDrugModel>();
            _selectedLeftDrug = new LeftDrugModel();
            _drugMethodCtrlList = new Dictionary<string, FrameworkElement>();
            CancleFinishCheckBoxEvent();

            InitialDrugTypeList();
            InitialDrugList();
            CreateDrugTypeGroupCtrlList();
            GetDisplayDrugCtrlList(_drugTypeGroupList.First().Code);
        }
        #endregion

        #region Properties
        public ObservableCollection<LeftDrugModel> ListLeftDrug
        {
            get
            {
                return _listLeftDrug;
            }

            set
            {
                _listLeftDrug = value;
            }
        }

        public ObservableCollection<AnesSystem.Controls.Operation.CQ.CQTL.MedicineElementCtrl> ListCtrl
        {
            get
            {
                return _listCtrl;
            }

            set
            {
                _listCtrl = value;
            }
        }

        public ConfigDrugsModel SelectedDrug
        {
            get
            {
                return _selectedDrug;
            }
            set
            {
                _selectedDrug = value;
                RaisePropertyChanged("SelectedDrug");
            }
        }

        public List<ConfigDrugMethodsModel> ConfigDrugMethodsModelList
        {
            get
            {
                return _configDrugMethodsModelList;
            }

            set
            {
                _configDrugMethodsModelList = value;
                RaisePropertyChanged("ConfigDrugMethodsModelList");
            }
        }

        public ConfigDrugMethodsModel SelectedDrugMethod
        {
            get
            {
                return _selectedDrugMethod;
            }

            set
            {
                if (value == null) return;
                _selectedDrugMethod = value;
                ChangeDrugDelieryWayPane();
                RaisePropertyChanged("SelectedDrugMethod");
            }
        }



        public LeftDrugModel SelectedLeftDrug
        {

            get
            {
                return _selectedLeftDrug;
            }
            set
            {
                if (value == null) return;
                _selectedLeftDrug = value;
                try
                {
                    PatientDrugsModel = _selectedLeftDrug.PatientDrug;
                    SetPatientDrug();
                }
                catch (Exception)
                {

                }
                RaisePropertyChanged("SelectedLeftDrug");
            }
        }

        public List<ConfigChannelsModel> ConfigChannelsModelList
        {
            get
            {
                return _configChannelsModelList;
            }

            set
            {
                _configChannelsModelList = value;
                RaisePropertyChanged("ConfigChannelsModelList");
            }
        }

        public FrameworkElement DrugMethodCtrl
        {
            get
            {
                return _drugMethodCtrl;
            }

            set
            {
                _drugMethodCtrl = value;
                RaisePropertyChanged("DrugMethodCtrl");
            }
        }

        public PatientDrugsModel PatientDrugsModelCopy
        {
            get
            {
                return _patientDrugsModelCopy;
            }

            set
            {
                _patientDrugsModelCopy = value;
                RaisePropertyChanged("PatientDrugsModelCopy");
            }
        }

        public int DialogType
        {
            get;
            set;

        }

        public int CurPage
        {
            get;
            set;
        }

        public Visibility LeftPanlVisibly
        {
            get
            {
                return _leftPanlVisibly;
            }

            set
            {
                _leftPanlVisibly = value;
                RaisePropertyChanged("LeftPanlVisibly");
            }
        }

        public DateTime PauseTime
        {
            get
            {
                return _pauseTime;
            }

            set
            {
                _pauseTime = value;
                RaisePropertyChanged("PauseTime");
            }
        }

        public DateTime RecoverTime
        {
            get
            {
                return _recoverTime;
            }

            set
            {
                _recoverTime = value;
                RaisePropertyChanged("RecoverTime");
            }
        }

        public bool FinishCheckBox
        {
            get
            {
                return _finishCheckBox;
            }

            set
            {
                _finishCheckBox = value;
                if (value)
                {
                    FinishCheckBoxEvent();
                }
                else
                {
                    CancleFinishCheckBoxEvent();
                }
                RaisePropertyChanged("FinishCheckBox");
            }
        }

        public bool TakeCheckBox
        {
            get
            {
                return _takeCheckBox;
            }

            set
            {
                _takeCheckBox = value;
                if (value)
                {
                    TakeCheckBoxEvent();
                }
                else
                {
                    CancleTakeCheckBoxEvent();
                }
                RaisePropertyChanged("TakeCheckBox");
            }
        }

        public Visibility FinishTimeVisibility
        {
            get
            {
                return _finishTimeVisibility;
            }

            set
            {
                _finishTimeVisibility = value;
                RaisePropertyChanged("FinishTimeVisibility");
            }
        }

        public Visibility TakeCheckBoxVisibility
        {
            get
            {
                return _takeCheckBoxVisibility;
            }

            set
            {
                _takeCheckBoxVisibility = value;
                RaisePropertyChanged("TakeCheckBoxVisibility");
            }
        }

        public Visibility TakeTextBlockVisibility
        {
            get
            {
                return _takeTextBlockVisibility;
            }

            set
            {
                _takeTextBlockVisibility = value;
                RaisePropertyChanged("TakeTextBlockVisibility");
            }
        }

        public Visibility TakeAmountVisibility
        {
            get
            {
                return _takeAmountVisibility;
            }

            set
            {
                _takeAmountVisibility = value;
                RaisePropertyChanged("TakeAmountVisibility");
            }
        }

        public Visibility TotalAmountUnitVisibility
        {
            get
            {
                return _totalAmountUnitVisibility;
            }

            set
            {
                _totalAmountUnitVisibility = value;
                RaisePropertyChanged("TotalAmountUnitVisibility");
            }
        }

        public Visibility PauseButtonVisibility
        {
            get
            {
                return _pauseButtonVisibility;
            }

            set
            {
                _pauseButtonVisibility = value;
                RaisePropertyChanged("PauseButtonVisibility");
            }
        }

        public Visibility RecoverButtonVisibility
        {
            get
            {
                return _recoverButtonVisibility;
            }

            set
            {
                _recoverButtonVisibility = value;
                RaisePropertyChanged("RecoverButtonVisibility");
            }
        }

        public PatientDrugsModel PatientDrugsModel
        {
            get
            {
                return _patientDrugsModel;
            }

            set
            {
                _patientDrugsModel = value;
                if (value != null)
                {
                    PatientDrugsModelCopy = value.ObjectToJsonM().JsonToObjectM<PatientDrugsModel>();
                }
                RaisePropertyChanged("PatientDrugsModel");
            }
        }

        public Visibility DeleteButtonVisibility
        {
            get
            {
                return _deleteButtonVisibility;
            }

            set
            {
                _deleteButtonVisibility = value;
                RaisePropertyChanged("DeleteButtonVisibility");
            }
        }

        public Visibility SaveAndContinueButtonVisibility
        {
            get
            {
                return _saveAndContinueButtonVisibility;
            }

            set
            {
                _saveAndContinueButtonVisibility = value;
                RaisePropertyChanged("SaveAndContinueButtonVisibility");
            }
        }

        public bool MaZuiIsCheck
        {
            get
            {
                return _maZuiIsCheck;
            }

            set
            {
                _maZuiIsCheck = value;
                RaisePropertyChanged("MaZuiIsCheck");
            }
        }

        public bool ShuYeIsCheck
        {
            get
            {
                return _shuYeIsCheck;
            }

            set
            {
                _shuYeIsCheck = value;
                RaisePropertyChanged("ShuYeIsCheck");
            }
        }

        public List<CustomEDBtnCtrl> DisplayDrugCtrlList
        {
            get
            {
                return _displayDrugCtrlList;
            }

            set
            {
                _displayDrugCtrlList = value;
                RaisePropertyChanged("DisplayDrugCtrlList");
            }
        }

        public Dictionary<string, List<ConfigDrugsModel>> DrugList
        {
            get
            {
                return _drugList;
            }

            set
            {
                _drugList = value;
                RaisePropertyChanged("DrugList");
            }
        }

        public ObservableCollection<ConfigDrugGroupTypesModel> DrugTypeGroupList
        {
            get
            {
                return _drugTypeGroupList;
            }

            set
            {
                _drugTypeGroupList = value;
            }
        }

        public Dictionary<string, List<CustomEDBtnCtrl>> DrugCtrlList
        {
            get
            {
                return _drugCtrlList;
            }

            set
            {
                _drugCtrlList = value;
                RaisePropertyChanged("DrugCtrlList");
            }
        }

        public ObservableCollection<CommonTypeCellCtrl> DrugTypeCtrlList
        {
            get
            {
                return _drugTypeCtrlList;
            }

            set
            {
                _drugTypeCtrlList = value;
            }
        }

        public CommonTypeCellCtrl CurrentSelType
        {
            get
            {
                return _currentSelType;
            }

            set
            {
                _currentSelType = value;
                RaisePropertyChanged("CurrentSelType");
            }
        }

        #endregion

        #region 依赖属性

        #endregion

        #region Event

        #endregion

        #region Private Methods
        public void InitialDrugList()
        {
            var list = DataManager.Instance.ConfigDrugsModelList.GroupBy(O => O.DrugGroupTypeCode);
            foreach (var item in list)
            {
                if (!string.IsNullOrEmpty(item.Key) && !_drugList.ContainsKey(item.Key))
                    _drugList.Add(item.Key, item.ToList());
            }
        }

        public void InitialDrugTypeList()
        {
            foreach (var item in DataManager.Instance.ConfigDrugGroupTypesModelList.ToList())
            //foreach (var item in DataManager.Instance.ConfigDrugGroupTypesModelList.Where(O => O.Deleted == false).ToList())
            {
                if (!string.IsNullOrEmpty(item.Code))
                    _drugTypeGroupList.Add(item);
            }
        }

        public void CreateDrugTypeGroupCtrlList()
        {
            foreach (var item in _drugTypeGroupList)
            {
                CommonTypeCellCtrl ctrl = new CommonTypeCellCtrl();
                ctrl.PreviewMouseLeftButtonDown += Type_PreviewMouseLeftButtonDown;
                ctrl.Tag = item;
                ctrl.Group = "group";
                ctrl.Display = item.Name;
                ctrl.FontSize = 16;
                ctrl.Margin = new System.Windows.Thickness(10, 5, 10, 0);
                DrugTypeCtrlList.Add(ctrl);
            }
        }

        public void GetDisplayDrugCtrlList(string group)
        {
            try
            {
                if (!string.IsNullOrEmpty(group))
                {
                    if (!_drugCtrlList.ContainsKey(group))
                    {
                        if (!_drugList.ContainsKey(group)) return;
                        List<ConfigDrugsModel> list = _drugList[group];
                        List<CustomEDBtnCtrl> listCtrl = new List<CustomEDBtnCtrl>();
                        foreach (var item in list)
                        {
                            CustomEDBtnCtrl ctrl = new CustomEDBtnCtrl();
                            ctrl.Clicked += Ctrl_Clicked;
                            ctrl.MouseLeftButtonDown += Drug_MouseLeftButtonDown;
                            ctrl.Margin = new System.Windows.Thickness(5);
                            ctrl.Tag = item;
                            ctrl.Display = item.Name;
                            listCtrl.Add(ctrl);
                        }
                        _drugCtrlList.Add(group, listCtrl);
                        DisplayDrugCtrlList = listCtrl;
                    }
                    else
                    {
                        DisplayDrugCtrlList = _drugCtrlList[group];
                    }
                }
            }
            catch (Exception ex)
            {
                Common.LogHelper.Error(this.GetType(), ex);
            }
        }

        public void Type_PreviewMouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            CommonTypeCellCtrl type = sender as CommonTypeCellCtrl;
            GetDisplayDrugCtrlList((type.Tag as ConfigDrugGroupTypesModel).Code);
        }
        public void Drug_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            CustomEDBtnCtrl ctrl = sender as CustomEDBtnCtrl;

        }
        public void Ctrl_Clicked(object sender, EventArgs e)
        {
            CustomEDBtnCtrl ctrl = sender as CustomEDBtnCtrl;
            ConfigDrugsModel cem = ctrl.Tag as ConfigDrugsModel;
            SelectedDrug = cem;
            if (SelectedDrug.Usage != null)
            {
                if ("drug_4".Equals(SelectedDrug.Usage) || "drug_5".Equals(SelectedDrug.Usage) ||
                    "drug_6".Equals(SelectedDrug.Usage) || "drug_11".Equals(SelectedDrug.Usage))
                {
                    SelectedDrugMethod = DataManager.Instance.ConfigDrugMethodsModelList.ToList().Where(O => O.Single == false && O.Code.Equals(SelectedDrug.Usage)).ToList().First();
                    ChangeDrugDelieryWayPane();
                }
            }
            AddDrug();
        }
        #endregion

        #region Public/Protected Methods

        //给药赋值
        public virtual void SetPatientDrug()
        {
            if (DialogType == 1)
            {
                foreach (var item in DrugTypeCtrlList)
                {
                    ConfigDrugGroupTypesModel group = item.Tag as ConfigDrugGroupTypesModel;
                    if ("drugGroupType_1".Equals(group.Code))
                    {
                        item.IsChecked = true;
                        GetDisplayDrugCtrlList(group.Code);
                        break;
                    }
                }
                MaZuiIsCheck = true;
                ShuYeIsCheck = false;
            }
            else if (DialogType == 2)
            {
                foreach (var item in DrugTypeCtrlList)
                {
                    ConfigDrugGroupTypesModel group = item.Tag as ConfigDrugGroupTypesModel;
                    if ("drugGroupType_3".Equals(group.Code))
                    {
                        item.IsChecked = true;
                        GetDisplayDrugCtrlList(group.Code);
                        break;
                    }
                }
                ShuYeIsCheck = true;
                MaZuiIsCheck = false;
            }
            //赋值弹框左边部分
            ListLeftDrug.Clear();
            LeftPanlVisibly = Visibility.Collapsed;
            List<PatientDrugsModel> PatientDrugList = OperationDataPool.Instance.CurOperationData.DrugsDataCache.AllPatientDrugsList.ToList();
            if (PatientDrugsModelCopy.Drugs.HashCode != null)
            {
                List<PatientDrugsModel> plist = PatientDrugList.FindAll(delegate (PatientDrugsModel p) { return p.Drugs.HashCode == PatientDrugsModelCopy.Drugs.HashCode; });//返回所有匹配
                if (plist != null && plist.Count > 1)
                {
                    plist = plist.OrderBy(O => O.BeginTime).ToList();
                    for (int i = 0; i < plist.Count; i++)
                    {
                        LeftDrugModel leftPDM = new LeftDrugModel();
                        leftPDM.Time = plist[i].BeginTime.ToString("t");
                        leftPDM.Frequency = "第" + (i + 1) + "次";
                        leftPDM.Color = "blue";
                        leftPDM.PatientDrug = plist[i];
                        ListLeftDrug.Add(leftPDM);
                    }
                    LeftPanlVisibly = Visibility.Visible;
                }
            }

            //赋值药的成分
            ListCtrl.Clear();
            if (PatientDrugsModelCopy.PatientID == null)
            {
                DeleteButtonVisibility = Visibility.Hidden;
                PauseButtonVisibility = Visibility.Hidden;
                RecoverButtonVisibility = Visibility.Hidden;
                SaveAndContinueButtonVisibility = Visibility.Visible;
                AddMedicCtrl();
            }
            else
            {
                foreach (var item in PatientDrugsModelCopy.Drugs.Items)
                {
                    AnesSystem.Controls.Operation.CQ.CQTL.MedicineElementCtrl medicineCtrl = new AnesSystem.Controls.Operation.CQ.CQTL.MedicineElementCtrl();
                    medicineCtrl.ConfigUnitsModelList = DataManager.Instance.ConfigUnitsModelList.ToList();
                    medicineCtrl.Item = item;
                    ListCtrl.Add(medicineCtrl);
                }
                DeleteButtonVisibility = Visibility.Visible;
                SaveAndContinueButtonVisibility = Visibility.Hidden;
            }
            //赋值药的用药方法
            if (PatientDrugsModelCopy.DrugMethod == null || PatientDrugsModelCopy.DrugMethod.Equals(""))
            {
                switch (DialogType)
                {
                    case 1:
                        {
                            PatientDrugsModelCopy.DrugMethod = Constants.DRUG_TCIBENGZHU;
                        }
                        break;
                    case 2:
                        {
                            PatientDrugsModelCopy.DrugMethod = Constants.DRUG__IVGTT;
                        }
                        break;
                }
            }
            SelectedDrugMethod = DataManager.Instance.ConfigDrugMethodsModelList.Where(O => O.Name != null && O.Name.Equals(PatientDrugsModelCopy.DrugMethod)).ToList().First();


            //赋值药的结束
            if (PatientDrugsModelCopy.EndTime != new DateTime() && Constants.ACTION_FINISH.Equals(PatientDrugsModelCopy.Status))
            {
                FinishCheckBox = true;
                //FinishTime = PatientDrugsModelCopy.EndTime;
                FinishTimeVisibility = Visibility.Visible;
                TakeCheckBoxVisibility = Visibility.Visible;

                //赋值药的带走
                if (PatientDrugsModelCopy.TakeOut)
                {
                    TakeCheckBoxEvent();
                    TakeCheckBox = true;
                    //TakeAmount = PatientDrugsModelCopy.TakeAmount;
                }
                else
                {
                    CancleTakeCheckBoxEvent();
                    TakeCheckBox = false;
                    //TakeAmount = "";
                }
            }
            else
            {
                CancleTakeCheckBoxEvent();
                CancleFinishCheckBoxEvent();
                TakeCheckBox = false;
                FinishCheckBox = false;
            }
            if (PatientDrugsModelCopy.PatientID == null)
            {
                RecoverButtonVisibility = Visibility.Hidden;
                PauseButtonVisibility = Visibility.Hidden;
            }
            else
            {
                if (PatientDrugsModelCopy.DrugSpeeds.Count < 1 || !PatientDrugsModelCopy.DrugSpeeds.Last().Actions.Equals(Constants.ACTION_PAUSE))
                {
                    RecoverButtonVisibility = Visibility.Hidden;
                    PauseButtonVisibility = Visibility.Visible;
                }
                else
                {
                    RecoverButtonVisibility = Visibility.Visible;
                    PauseButtonVisibility = Visibility.Hidden;
                }
            }
        }

        public void AddMedicCtrl()
        {
            AnesSystem.Controls.Operation.CQ.CQTL.MedicineElementCtrl ctrl = new AnesSystem.Controls.Operation.CQ.CQTL.MedicineElementCtrl();
            if (Constants.DRUG_XIRU.Equals(PatientDrugsModelCopy.DrugMethod) || Constants.DRUG_TCIBENGZHU.Equals(PatientDrugsModelCopy.DrugMethod))
            {
                ctrl.DoseEnable = false;
                ctrl.UnitEnable = false;
            }
            else
            {
                ctrl.DoseEnable = true;
                ctrl.UnitEnable = true;
            }
            ItemModel itemDrug = new ItemModel();
            ctrl.Item = itemDrug;
            ctrl.Height = 30;
            _patientDrugsModelCopy.Drugs.Items.Add(itemDrug);
            ctrl.ConfigUnitsModelList = DataManager.Instance.ConfigUnitsModelList.ToList();
            ListCtrl.Add(ctrl);
        }

        public void AddDrug()
        {
            for (int i = 0; i < ListCtrl.Count; i++)
            {
                if (ListCtrl[i].Item == null || ListCtrl[i].Item.Name.Equals("") || i == ListCtrl.Count() - 1)
                {
                    ItemModel itemDrug = new ItemModel();
                    itemDrug.Code = SelectedDrug.Code;
                    //itemDrug.Name = SelectedDrug.Name;
                    itemDrug.Name = string.Join("\u200B", SelectedDrug.Name.ToCharArray());
                    //itemDrug.Dose = SelectedDrug.Dose.ToString();
                    ConfigUnitsModel unit = DataManager.Instance.ConfigUnitsModelList.ToList().Find(delegate (ConfigUnitsModel u) { return u.Id.ToString() == SelectedDrug.UnitName; });
                    itemDrug.Unit = unit == null ? "ml" : unit.Name;
                    ListCtrl[i].Item = itemDrug;
                    PatientDrugsModelCopy.Drugs.Items[i] = itemDrug;
                    break;
                }
            }
        }

        public void DelDrug(AnesSystem.Controls.Operation.CQ.CQTL.MedicineElementCtrl ctrl)
        {
            if (ListCtrl.Count > 1)
            {
                ListCtrl.Remove(ctrl);
                PatientDrugsModelCopy.Drugs.Items.Remove(ctrl.Item);
            }
        }

        public void ChangeDrugDelieryWayPane()
        {
            //if (PatientDrugsModel.DrugMethod==null||"".Equals(PatientDrugsModel.DrugMethod)) {
            PatientDrugsModelCopy.DrugMethod = SelectedDrugMethod.Name;
            // }           
            foreach (var item in ListCtrl)
            {
                if (Constants.DRUG_XIRU.Equals(PatientDrugsModelCopy.DrugMethod) || Constants.DRUG_TCIBENGZHU.Equals(PatientDrugsModelCopy.DrugMethod))
                {
                    item.DoseEnable = false;
                    item.UnitEnable = false;
                }
                else
                {
                    item.DoseEnable = true;
                    item.UnitEnable = true;
                }
            }
            if (_drugMethodCtrlList.ContainsKey(SelectedDrugMethod.Code))
            {
                DrugMethodCtrl = _drugMethodCtrlList[SelectedDrugMethod.Code];
                ctrl = DrugMethodCtrl as BaseDrugMethodCtrl;
            }
            else
            {
                Type type = Type.GetType("AnesSystem.Controls." + SelectedDrugMethod.MethodCtrl);
                if (type != null)
                {
                    ctrl = Activator.CreateInstance(Type.GetType("AnesSystem.Controls." + SelectedDrugMethod.MethodCtrl)) as BaseDrugMethodCtrl;
                }
                else
                {
                    ctrl = Activator.CreateInstance(Type.GetType("AnesSystem.Controls.IvgttCtrl")) as BaseDrugMethodCtrl;
                }
                _drugMethodCtrlList.Add(SelectedDrugMethod.Code, ctrl);
                DrugMethodCtrl = ctrl;
            }
            if (PatientDrugsModelCopy.DrugMethod.Equals("吸入"))
            {
                ctrl.ConfigUnitsModelList = DataManager.Instance.ConfigUnitsModelList.ToList().Where(O => O.UnitTypeCode.Equals("unitType_2")).ToList();
            }
            else
            {
                ctrl.ConfigUnitsModelList = DataManager.Instance.ConfigUnitsModelList.ToList();
            }
            ctrl.PatientDrugs = PatientDrugsModelCopy;
            ctrl.Initial();

        }

        //保存一条用药记录
        public bool SavePatientDrug()
        {
            try
            {
                PatientDrugsModelCopy.BeginTime = PatientDrugsModelCopy.DrugSpeeds[0].BeginTime;

            }
            catch (Exception ex)
            {
                Common.LogHelper.Error(this.GetType(), ex);
            }
            if (CheckDrugTime())
            {
                PatientDrugsModelCopy.PatientID = DataManager.Instance.CurrentPatientLink.Id.ToString();
                PatientDrugsModelCopy.Type = DialogType == 2 ? Constants.DRUG_SHUYE : Constants.DRUG_SHUZHONG;
                if (DialogType == 2)
                {
                    PatientDrugsModelCopy.Type = Constants.DRUG_SHUYE;
                    if (PatientDrugsModelCopy.Chanel == null || "".Equals(PatientDrugsModelCopy.Chanel))
                    {
                        MessageBoxCommon.ShowDialog("未选择通道！！！", MessageBoxCommon.OK);
                        return false;
                    }
                }
                else
                {
                    PatientDrugsModelCopy.Type = Constants.DRUG_SHUZHONG;

                }
                PatientDrugsModelCopy.Drugs.HashCode = (AnesRecordUtil.Instance.GetTongLiangDrugHashCode(PatientDrugsModelCopy)).GetHashCode().ToString();
                PatientDrugsModelCopy.Drugs.FullName = AnesRecordUtil.Instance.GetTongLiangDrugFullName(PatientDrugsModelCopy);
                if (PatientDrugsModelCopy.LiquidType == null)
                {
                    List<ConfigDrugsModel> drugList = null;
                    List<ConfigDrugTypesModel> drugTypesList = null;
                    PatientDrugsModelCopy.LiquidType = "";
                    drugList = DataManager.Instance.ConfigDrugsModelList.Where(O => O.Deleted == false && O.Code != null && O.Code.Equals(PatientDrugsModelCopy.Drugs.Items[0].Code)).ToList();
                    if (drugList != null && drugList.Count > 0)
                    {
                        drugTypesList = DataManager.Instance.ConfigDrugTypesModelList.Where(O => O.Deleted == false && O.Code != null && O.Code.Equals(drugList.First().DrugTypeCode)).ToList();
                        if (drugTypesList != null && drugTypesList.Count > 0)
                            PatientDrugsModelCopy.LiquidType = drugTypesList.First().Name;
                    }
                }
                if (FinishCheckBox)
                {
                    PatientDrugsModelCopy.Status = Constants.ACTION_FINISH;
                    PatientDrugsModelCopy.TakeOut = TakeCheckBox;
                }
                else
                {
                    PatientDrugsModelCopy.Status = Constants.ACTION_WORK;
                    PatientDrugsModelCopy.EndTime = new DateTime();
                    PatientDrugsModelCopy.TakeOut = false;
                    PatientDrugsModelCopy.TakeAmount = "";
                }
                PatientDrugsModelCopy.DrugSpeeds = PatientDrugsModelCopy.DrugSpeeds.OrderBy(O => O.BeginTime).ToList();
                if (Constants.DRUG_SHUZHONG.Equals(PatientDrugsModelCopy.Type) && Constants.DRUG__IVGTT.Equals(PatientDrugsModelCopy.DrugMethod))
                {
                    double dose = 0;
                    foreach (var item in PatientDrugsModelCopy.Drugs.Items)
                    {
                        dose += item.Dose.ToDouble();
                    }
                    PatientDrugsModelCopy.DrugSpeeds[0].Speed = dose.ToString();
                }
                if (Constants.DRUG_BENGZHU.Equals(PatientDrugsModelCopy.DrugMethod))
                {
                    PatientDrugsModelCopy.Yongliang = AnesRecordUtil.Instance.GetRealYeTi(PatientDrugsModelCopy).ToString();
                    PatientDrugsModelCopy.YongliangUnit = AnesRecordUtil.Instance.GetJiLiangUnit(PatientDrugsModelCopy);
                }

                OperationDataPool.Instance.CurOperationData.DrugsDataCache.AddAndUpdateExe(PatientDrugsModelCopy);
                //AddConfigDrug();
                for (int i = 1; i <= DataManager.Instance.CurrentPatientLink.Status.TotalPage; i++)
                {
                    (DataManager.Instance.AnesRecordCtrl.DataContext as AnesRecordCtrlViewModel).AnesRecordCtrlViewModels[i].AnesMedicineCtrlViewModel.Refresh();
                    (DataManager.Instance.AnesRecordCtrl.DataContext as AnesRecordCtrlViewModel).AnesRecordCtrlViewModels[i].AnesInfusionCtrlViewModel.Refresh();
                }
                OperationDetailsViewModel.Instance.Refresh();
                return true;
            }
            else
            {
                return false;
            }
        }

        public bool CheckDrugTime()
        {
            foreach (var item in PatientDrugsModelCopy.Drugs.Items)
            {
                if (null == item || string.IsNullOrEmpty(item.Code))
                {
                    MessageBoxCommon.ShowDialog("请输入药名", MessageBoxCommon.OK);
                    return false;
                }
            }
            if (PatientDrugsModelCopy.BeginTime != new DateTime() && PatientDrugsModelCopy.BeginTime.CompareTo(DataManager.Instance.CurrentPatientLink.Status.InRoomTime) < 0)
            {
                MessageBoxCommon.ShowDialog("开始时间应大于入室时间", MessageBoxCommon.OK);
                return false;
            }
            if (DataManager.Instance.CurrentPatientLink.Status.OutRoomTime != new DateTime() && PatientDrugsModelCopy.BeginTime.CompareTo(DataManager.Instance.CurrentPatientLink.Status.OutRoomTime) > 0)
            {
                MessageBoxCommon.ShowDialog("开始时间应小于出室时间", MessageBoxCommon.OK);
                return false;
            }

            if (PatientDrugsModelCopy.EndTime != new DateTime() && PatientDrugsModelCopy.EndTime.CompareTo(PatientDrugsModelCopy.BeginTime) < 0)
            {
                MessageBoxCommon.ShowDialog("结束时间应大于开始时间", MessageBoxCommon.OK);
                return false;
            }
            if (DataManager.Instance.CurrentPatientLink.Status.OutRoomTime != new DateTime() && PatientDrugsModelCopy.EndTime != new DateTime() &&
                PatientDrugsModelCopy.EndTime.CompareTo(DataManager.Instance.CurrentPatientLink.Status.OutRoomTime) > 0)
            {
                MessageBoxCommon.ShowDialog("结束时间应小于出室时间", MessageBoxCommon.OK);
                return false;
            }
            return true;
        }


        public void AddConfigDrug()
        {
            foreach (var item in PatientDrugsModelCopy.Drugs.Items)
            {
                List<ConfigDrugsModel> DrugsList = DataManager.Instance.ConfigDrugsModelList.Where(O => O.Name.Equals(item.Name)).ToList();
                ConfigDrugsModel pDrug = DrugsList.Find(delegate (ConfigDrugsModel p) { return p.Name == item.Name; });//只返回第一个匹配
                if (pDrug == null)
                {
                    ConfigDrugsModel drug = new ConfigDrugsModel();
                    drug.Code = "drug_" + DateTime.Now.Ticks;
                    drug.Deleted = false;
                    drug.Name = item.Name;
                    drug.Dose = item.Dose.ToDouble();
                    drug.UnitName = item.Unit;
                    drug.DrugGroupTypeCode = "drugGroupType_6";
                    drug.DrugTypeCode = "drugType_1";
                    drug.PrescriptionName = "普通";
                    drug.PrescriptionTypeCode = "普通";
                    drug.Usage = "drug_7";
                    drug.IsEnd = "Visible";
                    drug.IsTakeAway = "Visible";
                    DataManager.Instance.ConfigDrugsModelList.Add(drug);
                    ConfigDrugsModelService.Instance.Update(drug);
                }
            }
        }

        //删除一条用药记录

        public void DeletePatientDrug()
        {
            PatientDrugsModelCopy.Status = "invalid";
            OperationDataPool.Instance.CurOperationData.DrugsDataCache.AddAndUpdateExe(PatientDrugsModelCopy);
            //AnesRecordUtil.Instance.CalLiquidInAndOut(PatientDrugsModel, PatientDrugsModelCopy);
            for (int i = 1; i <= DataManager.Instance.CurrentPatientLink.Status.TotalPage; i++)
            {
                (DataManager.Instance.AnesRecordCtrl.DataContext as AnesRecordCtrlViewModel).AnesRecordCtrlViewModels[i].AnesMedicineCtrlViewModel.Refresh();
                (DataManager.Instance.AnesRecordCtrl.DataContext as AnesRecordCtrlViewModel).AnesRecordCtrlViewModels[i].AnesInfusionCtrlViewModel.Refresh();
            }
            OperationDetailsViewModel.Instance.Refresh();
        }
        //暂停按钮
        public void PausePatientDrug()
        {
            DrugSpeedModel drugSpeed = new DrugSpeedModel();
            drugSpeed.BeginTime = PauseTime;
            drugSpeed.Actions = Constants.ACTION_PAUSE;
            PatientDrugsModelCopy.DrugSpeeds.Add(drugSpeed);
            PatientDrugsModelCopy.Status = Constants.ACTION_PAUSE;
            ChangeDrugDelieryWayPane();
            RecoverButtonVisibility = Visibility.Visible;
            PauseButtonVisibility = Visibility.Hidden;
        }

        public void RecoverPatientDrug()
        {
            DrugSpeedModel drugSpeed = new DrugSpeedModel();
            drugSpeed.BeginTime = RecoverTime;
            if (!Constants.DRUG__IVGTT.Equals(PatientDrugsModelCopy.DrugMethod))
                drugSpeed.Speed = PatientDrugsModelCopy.DrugSpeeds[0].Speed;
            drugSpeed.Unit = PatientDrugsModelCopy.DrugSpeeds[0].Unit;
            PatientDrugsModelCopy.DrugSpeeds.Add(drugSpeed);
            ChangeDrugDelieryWayPane();
            RecoverButtonVisibility = Visibility.Hidden;
            PauseButtonVisibility = Visibility.Visible;
        }

        public void Excute(string commond)
        {
            DataManager.Instance.IsNotNeedSaveData = false;
            switch (commond)
            {
                case "Delete":
                    {
                        DeletePatientDrug();
                        DrugAndEventWindow.Instance.CusContent = MedicineConfigDialogCtrl.Instance;
                        DrugAndEventWindow.Instance.CloseWin(false);
                    }
                    break;
                case "Cancel":
                    {
                        PatientDrugsModelCopy = PatientDrugsModel.ObjectToJsonM().JsonToObjectM<PatientDrugsModel>();
                        DrugAndEventWindow.Instance.CusContent = MedicineConfigDialogCtrl.Instance;
                        DrugAndEventWindow.Instance.CloseWin(false);
                    }
                    break;
                case "Pause":
                    {
                        CusDatePickerWin cusDatePicker = new CusDatePickerWin();
                        cusDatePicker.SelectedDateTime = DateTime.Now;
                        cusDatePicker.ShowDialog();
                        if (cusDatePicker.Result)
                        {
                            if (cusDatePicker.SelectedDateTime.CompareTo(PatientDrugsModelCopy.BeginTime) < 0)
                            {
                                MessageBoxCommon.ShowDialog("暂停时间时间应大于入室时间", MessageBoxCommon.OK);
                            }
                            else
                            {
                                PauseTime = cusDatePicker.SelectedDateTime;
                                PausePatientDrug();
                            }
                        }
                        else
                        {
                            PauseTime = new DateTime();
                        }
                    }
                    break;
                case "Recover":
                    {
                        CusDatePickerWin cusDatePicker = new CusDatePickerWin();
                        cusDatePicker.SelectedDateTime = DateTime.Now;
                        cusDatePicker.ShowDialog();
                        if (cusDatePicker.Result)
                        {
                            if (cusDatePicker.SelectedDateTime.CompareTo(PatientDrugsModelCopy.BeginTime) < 0)
                            {
                                MessageBoxCommon.ShowDialog("恢复时间时间应大于入室时间", MessageBoxCommon.OK);
                            }
                            else
                            {
                                RecoverTime = cusDatePicker.SelectedDateTime;
                                RecoverPatientDrug();
                            }
                        }
                        else
                        {
                            RecoverTime = new DateTime();
                        }
                    }
                    break;
                case "SaveAndContinue":
                    {
                        if (SavePatientDrug())
                        {
                            PatientDrugsModel = new PatientDrugsModel();
                            SetPatientDrug();
                        }
                    }
                    break;
                case "Save":
                    {
                        if (SavePatientDrug())
                        {
                            DrugAndEventWindow.Instance.CusContent = MedicineConfigDialogCtrl.Instance;
                            DrugAndEventWindow.Instance.CloseWin(false);
                        }

                    }
                    break;
            }
        }

        public void FinishCheckBoxEvent()
        {
            FinishTimeVisibility = Visibility.Visible;
            TakeCheckBoxVisibility = Visibility.Visible;
            if (PatientDrugsModelCopy.EndTime == new DateTime())
            {
                PatientDrugsModelCopy.EndTime = DateTime.Now;
            }
        }

        public void CancleFinishCheckBoxEvent()
        {
            FinishTimeVisibility = Visibility.Hidden;
            TakeCheckBoxVisibility = Visibility.Hidden;
            TakeTextBlockVisibility = Visibility.Hidden;
            TakeAmountVisibility = Visibility.Hidden;
            TotalAmountUnitVisibility = Visibility.Hidden;
        }

        public void TakeCheckBoxEvent()
        {
            TakeTextBlockVisibility = Visibility.Visible;
            TakeAmountVisibility = Visibility.Visible;
            TotalAmountUnitVisibility = Visibility.Visible;

        }

        public void CancleTakeCheckBoxEvent()
        {
            TakeTextBlockVisibility = Visibility.Hidden;
            TakeAmountVisibility = Visibility.Hidden;
            TotalAmountUnitVisibility = Visibility.Hidden;
        }


        #endregion

        #region EventHandlers

        #endregion




    }
}
